﻿using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Xml;
using VisualWip.PresentationModel.Text;

namespace VisualWip
{
    /// <summary>
    /// Interaction logic for RichTextViewer.xaml
    /// </summary>
    public partial class RichTextViewer : UserControl
    {
        private RichTextColumnViewModel _textColumn;

        public RichTextViewer()
        {
            InitializeComponent();
        }

        private void UserControlDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var columnViewModel = e.NewValue as RichTextColumnViewModel;
            if (columnViewModel != null)
            {
                _textColumn = columnViewModel;
                UpdateText();
                _textColumn.PropertyChanged += TextColumnPropertyChanged;
            }
            else
            {
                _textColumn.PropertyChanged -= TextColumnPropertyChanged;
                _textColumn = null;
            }
        }

        private void TextColumnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            UpdateText();
        }


        private void UpdateText()
        {
            if (!string.IsNullOrEmpty(_textColumn.Document))
            {
                var stringReader = new StringReader(_textColumn.Document);
                XmlReader xmlReader = XmlReader.Create(stringReader);
                TextViewer.Document = (FlowDocument)XamlReader.Load(xmlReader);
            }
        }
    }
}